package rendering;

import hulppakket.CgPanel;
import hulppakket.Color3f;
import hulppakket.Intersection;
import hulppakket.Scene;

import java.io.FileNotFoundException;

import javax.swing.JFrame;

import parser.SceneBuilder;

public class RayTracer {

	private SceneBuilder builder;
	private JFrame frame;
	float nx, ny;
	private CgPanel panel;
	private Color3f[][] pixels;
	private Scene scene;
	private int aasamples = 5;

	public RayTracer(float nx, float ny) {
		this.nx = nx;
		this.ny = ny;
		try {
			initializeFrame();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void draw() {
		Color3f color;
		for (int i = 0; i < nx; i++) {
			for (int j = 0; j < ny; j++) {
				color = this.pixels[i][j];
				panel.drawPixel(i, j, color.x, color.y, color.z);
			}
		}
	}

	private void initializeFrame() throws FileNotFoundException {
		builder = new SceneBuilder();
		scene = builder.loadScene("src/XML/test2.sdl");
		frame = new JFrame();
		frame.setSize((int) nx, (int) ny);
		panel = new CgPanel();
		frame.getContentPane().add(panel);
		frame.setVisible(true);
		pixels = new Color3f[(int) nx][(int) ny];
	}

	public void trace() throws InterruptedException {
		Thread.sleep(500);
		Intersection intersection = null;
		long start = System.currentTimeMillis();
		for (int i = 0; i < this.scene.getCurrentCamera().getNx(); i++) {
			System.out.println((i / this.nx) * 100 + "% done...");
			for (int j = 0; j < this.scene.getCurrentCamera().getNy(); j++) {
				Color3f color = new Color3f();
				for (int p = 0; p < aasamples; p++) {
					for (int q = 0; q < aasamples; q++) {
						if (!(aasamples == 1)) {
							float ia, ja;
							ia = (float) (i + (p + Math.random()) / aasamples);
							ja = (float) (j + (q + Math.random()) / aasamples);
							intersection = this.scene.getIntersection(ia, ja);
						} else {
							intersection = this.scene.getIntersection(i, j);
						}
						if (intersection != null) {
							color = color.add(intersection.getColor(scene));
						}
					}
				}
				this.pixels[i][j] = color.scale((float) (1f / Math.pow(
						aasamples, 2)));
			}
		}
		long end = System.currentTimeMillis();
		this.draw();
		System.out.println((end - start) + " milisec");
		panel.repaint();
		System.out.println("Done");
	}
}
